'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs-promise';
import * as path from 'path';
import { uniq } from 'lodash';
const bootstrap = require('../../res/bootstrap.json')
const qi = require('../../res/qi.json')


export async function scanLessClassInDir(dir: string): Promise<string[]> {
    let ret: string[] = [];
    const r = await fs.readdir(dir)
    for (let i of r) {
        if (!i.endsWith('.less') && !i.endsWith('.css')) {
            continue
        }
        const c = await fs.readFile(path.join(dir, i), 'utf8')
        let match: any
        const reg = /\.([0-9a-zA-Z-]*)[\s,{:]/g
        while (match = reg.exec(c)) {
            if (match.length > 1) {
                const s = match[1]
                if (s.length >= 3) {
                    ret.push(s)
                }
            }

        }
    }
    return uniq(ret);
}


class LessCompletionItemProvider implements vscode.CompletionItemProvider {

    // provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): CompletionItem[] | Thenable<CompletionItem[]> | CompletionList | Thenable<CompletionList>;

    public provideCompletionItems(
        document: vscode.TextDocument,
        position: vscode.Position,
        token: vscode.CancellationToken,
    ): Thenable<vscode.CompletionItem[]> {
        return new Promise((resolve, reject) => {
            const dir = path.dirname(document.fileName)
            scanLessClassInDir(dir).then(res => {
                console.log('res', res)
                res = res.concat(bootstrap, qi)
                resolve(res.map(v => new vscode.CompletionItem(v, vscode.CompletionItemKind.Variable)));
            }).catch(err => {
                console.log('err', err)
                reject(err)
            })
        })
    }
}

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(ctx: vscode.ExtensionContext) {

    console.info('Congratulations, your extension "html-less-class-completion-" is now active!');

    ctx.subscriptions.push(vscode.languages.registerCompletionItemProvider(
        'html',
        new LessCompletionItemProvider(),
        '.', '\"'
    ))
    ctx.subscriptions.push(vscode.languages.registerCompletionItemProvider(
        'typescriptreact',
        new LessCompletionItemProvider(),
        '.', '\"'
    ))
    ctx.subscriptions.push(vscode.languages.registerCompletionItemProvider(
        'javascriptreact',
        new LessCompletionItemProvider(),
        '.', '\"'
    ))
}

// this method is called when your extension is deactivated
export function deactivate() {
}
